package com.prp.gwt.client.widgets.admin;

import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.prp.gwt.client.admin.AdminHistoryHandler;
import com.prp.gwt.client.admin.AdminListener;
import com.prp.gwt.client.vo.Community;
import com.prp.gwt.client.vo.CommunityList;

public class CommunityListPanel extends VerticalPanel{

	private static CommunityListPanel instance;
	private FlexTable table = new FlexTable();
	private HTML message = new HTML();
	
	public static CommunityListPanel getInstance() {
		if (instance == null)
			instance = new CommunityListPanel();
		return instance;
	}

	public CommunityListPanel() {
		Timer timer = new Timer() {

			@Override
			public void run() {
				if (CommunityListPanel.this.isVisible())
					AdminListener.getInstance().updateCommunityList();
			}

		};
		timer.scheduleRepeating(5000);

		Button divideButton = new Button("划分社区");
		divideButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				AdminListener.getInstance().divideCommunity();
			}

		});
		Button refreshButton = new Button("刷新");
		refreshButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				AdminListener.getInstance().updateCommunityList();
				setMessage("正在刷新");
			}
		});
		HorizontalPanel panel = new HorizontalPanel();
		panel.add(divideButton);
		panel.add(refreshButton);
		panel.add(message);
		panel.setSpacing(10);

		HTML undivided = new HTML("<a>查看未划分社区的用户列表</a>");
		undivided.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				History.newItem(AdminHistoryHandler.COMMUNITY+AdminHistoryHandler.UNDIVIDED);
			}
		});

		table.setHTML(0, 0, "社区ID");
		table.setHTML(0, 1, "社区人数");
		table.setCellSpacing(10);

		add(panel);
		add(undivided);
		add(table);
	}

	public void setMessage(String text) {
		message.setText(text);
	}

	public void load(CommunityList communityList) {
		int row = table.getRowCount();
		for (int i = row - 1; i > 0; i--)
			table.removeRow(i);
		final List<Community> list = communityList.getCommunities();
		for (int i = 0; i < list.size(); i++) {
			int j = i + 1;
			table.setHTML(j, 0, String.valueOf(list.get(i).getId()));
			table.setHTML(j, 1, String.valueOf(list.get(i).getNum()));
			HTML link = new HTML("<a>查看</a>");
			final int k = i;
			link.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					History.newItem(AdminHistoryHandler.COMMUNITY+k);
				}
			});
			table.setWidget(j, 2, link);
		}
		setMessage("");
	}

}
